<template>
  <div class="student-management">
    <div class="page-header">
      <h2>学生管理</h2>
      <el-button type="primary" @click="handleAddStudent">
        <el-icon><plus /></el-icon>
        添加学生
      </el-button>
    </div>
    
    <!-- 搜索和筛选 -->
    <div class="search-filter">
      <el-input
        v-model="searchQuery"
        placeholder="搜索学生姓名、学号"
        prefix-icon="Search"
        style="width: 300px;"
        @keyup.enter="handleSearch"
      >
      </el-input>
      
      <el-select v-model="classFilter" placeholder="选择班级" style="width: 150px; margin-left: 16px;">
        <el-option label="全部班级" value=""></el-option>
        <el-option label="计算机科学一班" value="1"></el-option>
        <el-option label="计算机科学二班" value="2"></el-option>
        <el-option label="软件工程一班" value="3"></el-option>
        <el-option label="软件工程二班" value="4"></el-option>
      </el-select>
      
      <el-button @click="handleSearch" style="margin-left: 16px;">搜索</el-button>
      <el-button @click="handleReset" style="margin-left: 8px;">重置</el-button>
    </div>
    
    <!-- 学生表格 -->
    <el-card class="table-card" style="margin-top: 16px;">
      <el-table
        v-loading="loading"
        :data="studentsData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="id" label="学号" width="120" sortable></el-table-column>
        <el-table-column prop="name" label="姓名" width="120" sortable></el-table-column>
        <el-table-column prop="gender" label="性别" width="80">
          <template #default="scope">
            <span>{{ scope.row.gender === 'male' ? '男' : '女' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="age" label="年龄" width="80" sortable></el-table-column>
        <el-table-column prop="class" label="班级" width="180"></el-table-column>
        <el-table-column prop="major" label="专业" width="150"></el-table-column>
        <el-table-column prop="phone" label="电话" width="150"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="200"></el-table-column>
        <el-table-column prop="enrollmentDate" label="入学日期" width="150" sortable>
          <template #default="scope">
            <span>{{ formatDate(scope.row.enrollmentDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="handleEditStudent(scope.row)">编辑</el-button>
            <el-button type="danger" link @click="handleDeleteStudent(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 分页 -->
    <div class="pagination" style="margin-top: 16px;">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 添加/编辑学生对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      @close="handleDialogClose"
    >
      <el-form
        ref="studentFormRef"
        :model="studentForm"
        :rules="studentRules"
        label-width="100px"
      >
        <el-form-item label="学号" prop="id">
          <el-input v-model="studentForm.id" :disabled="isEditMode"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="studentForm.name"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="studentForm.gender">
            <el-radio label="male">男</el-radio>
            <el-radio label="female">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model.number="studentForm.age" type="number"></el-input>
        </el-form-item>
        <el-form-item label="班级" prop="class">
          <el-select v-model="studentForm.class">
            <el-option label="计算机科学一班" value="计算机科学一班"></el-option>
            <el-option label="计算机科学二班" value="计算机科学二班"></el-option>
            <el-option label="软件工程一班" value="软件工程一班"></el-option>
            <el-option label="软件工程二班" value="软件工程二班"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="专业" prop="major">
          <el-input v-model="studentForm.major"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="studentForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="studentForm.email"></el-input>
        </el-form-item>
        <el-form-item label="入学日期" prop="enrollmentDate">
          <el-date-picker
            v-model="studentForm.enrollmentDate"
            type="date"
            placeholder="选择日期"
            style="width: 100%;"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveStudent">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { Plus, Search } from '@element-plus/icons-vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

// 搜索和筛选条件
const searchQuery = ref('')
const classFilter = ref('')

// 表格数据
const studentsData = ref([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const selectedStudents = ref([])

// 对话框相关
const dialogVisible = ref(false)
const isEditMode = ref(false)
const dialogTitle = computed(() => isEditMode.value ? '编辑学生' : '添加学生')
const studentFormRef = ref(null)
const studentForm = reactive({
  id: '',
  name: '',
  gender: 'male',
  age: '',
  class: '',
  major: '',
  phone: '',
  email: '',
  enrollmentDate: ''
})

// 表单验证规则
const studentRules = {
  id: [
    { required: true, message: '请输入学号', trigger: 'blur' },
    { pattern: /^\d+$/, message: '学号必须为数字', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' },
    { type: 'number', min: 16, max: 30, message: '年龄在 16 到 30 之间', trigger: 'blur' }
  ],
  class: [
    { required: true, message: '请选择班级', trigger: 'change' }
  ],
  major: [
    { required: true, message: '请输入专业', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  enrollmentDate: [
    { required: true, message: '请选择入学日期', trigger: 'change' }
  ]
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

// 加载学生数据
const loadStudents = async () => {
  loading.value = true
  try {
    // 真实的API调用
    const response = await axios.get('/api/students', {
      params: {
        page: currentPage.value,
        pageSize: pageSize.value,
        keyword: searchQuery.value,
        classId: classFilter.value
      }
    })
    studentsData.value = response.data.data
    total.value = response.data.total
  } catch (error) {
    console.error('加载学生数据失败:', error)
    ElMessage.error('加载学生数据失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  loadStudents()
}

// 处理重置
const handleReset = () => {
  searchQuery.value = ''
  classFilter.value = ''
  currentPage.value = 1
  loadStudents()
}

// 处理分页大小变化
const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  loadStudents()
}

// 处理页码变化
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
  loadStudents()
}

// 处理选择变化
const handleSelectionChange = (selection) => {
  selectedStudents.value = selection
}

// 打开添加学生对话框
const handleAddStudent = () => {
  isEditMode.value = false
  // 重置表单
  Object.keys(studentForm).forEach(key => {
    studentForm[key] = key === 'gender' ? 'male' : ''
  })
  dialogVisible.value = true
}

// 打开编辑学生对话框
const handleEditStudent = (row) => {
  isEditMode.value = true
  // 填充表单
  Object.assign(studentForm, row)
  dialogVisible.value = true
}

// 保存学生
const handleSaveStudent = async () => {
  try {
    await studentFormRef.value.validate()
    
    // 真实的API调用
    if (isEditMode.value) {
      await axios.put(`/api/students/${studentForm.id}`, studentForm)
      ElMessage.success('学生信息更新成功')
    } else {
      await axios.post('/api/students', studentForm)
      ElMessage.success('学生添加成功')
    }
    
    dialogVisible.value = false
    loadStudents()
  } catch (error) {
    console.error('保存学生数据失败:', error)
    ElMessage.error('保存学生数据失败，请稍后重试')
  }
}

// 删除学生
const handleDeleteStudent = (id) => {
  ElMessageBox.confirm(
    '确定要删除这个学生吗？删除后将无法恢复。',
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      // 真实的API调用
      await axios.delete(`/api/students/${id}`)
      ElMessage.success('学生删除成功')
      loadStudents()
    })
    .catch(() => {
      // 用户取消删除
    })
}

// 关闭对话框
const handleDialogClose = () => {
  if (studentFormRef.value) {
    studentFormRef.value.resetFields()
  }
}

// 初始加载数据
loadStudents()
</script>

<style scoped>
.student-management {
  height: 100%;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.page-header h2 {
  margin: 0;
  font-size: 20px;
  color: #333;
}

.search-filter {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

@media (max-width: 768px) {
  .search-filter {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }
  
  .search-filter .el-input,
  .search-filter .el-select {
    width: 100% !important;
  }
  
  .search-filter .el-button {
    margin-left: 0 !important;
  }
  
  .page-header {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }
}
</style>